package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.SearchResultAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_Serach;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SearchDeviceActivity1 extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mTypeTv;
	private Button mNextstepB;
	private TextView mResultT;
	private ListView mResultLv;
	private SearchResultAdapter mAdapter;
	private TextView tv_statusBar_mian;
	// private RippleBackground rippleBackground;
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private boolean searching = true;
//	private int[] rfLight = new int[] { 1, 255, 255, 255, 255, 4, 65, 0, 0, 0 };
//	private int[] rfLight2 = new int[] { 1, 255, 255, 255, 255, 16, 65, 0, 0, 0 };
//	private int[] cwLight = new int[] { 1, 255, 255, 255, 255, 10, 65, 0, 0, 0 };
//	private int[] rfswitch = new int[] { 1, 255, 255, 255, 255, 37, 65, 0, 0, 0 };
//	private int[] cwSocket = new int[] { 1, 255, 255, 255, 255, 1, 65, 0, 0, 0 };
	private int[] rfLight = new int[] { 1, 255, 255, 255, 255, 4, 67, 0, 0, 0 };
	private int[] rfLight2 = new int[] { 1, 255, 255, 255, 255, 16, 67, 0, 0, 0 };
	private int[] cwLight = new int[] { 1, 255, 255, 255, 255, 10, 67, 0, 0, 0 };
	private int[] rfswitch = new int[] { 1, 255, 255, 255, 255, 37, 67, 0, 0, 0 };
	private int[] cwSocket = new int[] { 1, 255, 255, 255, 255, 1, 67, 0, 0, 0 };
	private String searchCmd;
	private int type;
	private MySocket socket;
	private boolean isSearching = false;
	private String deviceAddress;
	private List<Device> mDeviceList = new ArrayList<Device>();
	private int sendCmdTimes;
	private String deviceType;
	private SVProgressHUD mSVProgressHUD;
	private int mUpLoadCounts = 0;
	private int count = 0;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			if (mDeviceList.size() == 0) {
				if (!searching) {
					finish();
				} else {
					exit();
				}
			} else {
				exit1();
			}
			break;
		case R.id.nextstep:
			// 先检查名称是否重复 要在全部设备中检查，否则如果名字重复会导致设备无法控制
			mDeviceList = mAdapter.getData();
			for (int i = 0; i < mDeviceList.size(); i++) {
				mDeviceList.get(i).existed = false;
			}
			String temp = "";
			boolean e1 = false;
			for (int i = 0; i < mDeviceList.size() - 1; i++) {
				temp = mDeviceList.get(i).getDeviceName();
				if (temp.length() < 2) {
					ToastShow.Show(getApplicationContext(),
							getString(R.string.device_name_not_vaild));
					return;
				}
				for (int j = i + 1; j < mDeviceList.size(); j++) {
					if (temp.equals(mDeviceList.get(j).getDeviceName())) {
						Log.i("wmy", "第" + (i + 1) + "个跟第" + (j + 1)
								+ "个重复，值是：" + temp);
						mDeviceList.get(i).existed = true;
						mDeviceList.get(j).existed = true;
						e1 = true;
					}
				}
			}
			boolean rename = false;
			for (int i = 0; i < mDeviceList.size(); i++) {
				Log.i("wmy", "保存设备" + mDeviceList.get(i).getDeviceName());
				boolean e = DeviceManager.getInstance().checkName(
						mDeviceList.get(i).getDeviceName());
				if (e) {
					rename = true;
					mDeviceList.get(i).existed = true;
				}
			}
			if (rename || e1) {
				mAdapter.notifyDataSetChanged();
				ToastShow.Show(getApplicationContext(),
						getString(R.string.device_exists2));
				return;
			} else {
				// 再提交
				for (int i = 0; i < mDeviceList.size(); i++) {
					DeviceManager.getInstance().addSaveDevice(
							mDeviceList.get(i));
				}
				AddTypeSelectionActivity1.addTypeSelectionActivity1.finish();
				finish();
			}
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mDeviceList.size() == 0) {
				if (!searching) {
					finish();
				} else {
					exit();
				}
			} else {
				exit1();
			}
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void exit() {
		mNormalDialog = new NormalDialog(SearchDeviceActivity1.this);
		mNormalDialog.content("您正在搜索智能家电设备，是否返回？")
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				finish();
			}

		});
	}

	private void exit1() {
		mNormalDialog = new NormalDialog(SearchDeviceActivity1.this);
		mNormalDialog.content("您有搜索到的智能家电设备尚未保存，是否返回？")
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				finish();
			}

		});
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				searching = false;
				// rippleBackground.stopRippleAnimation();
				// rippleBackground.setVisibility(View.GONE);
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				mResultLv.setVisibility(View.VISIBLE);
				socket.setNotReceiving(true);
				socket.setSendHeartBeatTime(System.currentTimeMillis());
				socket.setReceiveHeartBeatTime(System.currentTimeMillis());
				if (mDeviceList.size() == 0) {
					mResultT.setText("共搜索到0个" + deviceType);
					Toast toast = Toast.makeText(
							getApplicationContext(),
							getResources().getString(
									R.string.none_device_search),
							Toast.LENGTH_SHORT);
					toast.show();
				} else {
					mResultT.setText("共搜索到" + mDeviceList.size() + "个"
							+ deviceType);
					mNextstepB.setVisibility(View.VISIBLE);
					mAdapter = new SearchResultAdapter(getApplicationContext(),
							mDeviceList);
					mResultLv.setAdapter(mAdapter);
				}
				break;
			case 1:
				int count = msg.arg1;
				count++;
				if (count < mDeviceList.size()) {
					// upLoadDevices(count);
				} else {
					Toast.makeText(getApplicationContext(), "设备绑定成功！",
							Toast.LENGTH_SHORT).show();
					mDeviceList.clear();
					AddTypeSelectionActivity.addTypeSelectionActivity.finish();
					AddDeviceTypeSelectionActivity.addDeviceTypeSelectionActivity
							.finish();
					finish();
				}
				break;
			case 2:
				finish();
				break;
			case 3:
				adjustConnectState();
				break;
			default:
				break;
			}
		}
	};

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_search_device;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mTypeTv = $(R.id.search_type_tv);
		mNextstepB = $(R.id.nextstep);
		mNextstepB.setText(getResources().getString(R.string.save));
		mResultT = $(R.id.result_tv);
		mResultLv = $(R.id.result_lv);
		mBackL.setOnClickListener(this);
		mNextstepB.setOnClickListener(this);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		// rippleBackground = $(R.id.content);
		mSVProgressHUD = new SVProgressHUD(SearchDeviceActivity1.this);
		boolVersion();
		type = getIntent().getIntExtra("type", 0);
		switch (type) {
		case DeviceType.DEVICE_TYPE_SOCKET:
			mTypeTv.setText("搜索智能插座");
			deviceType = "智能插座";
			searchCmd = ConvertUtil.getInstance().convertSearchCmd(cwSocket);
			break;
		case DeviceType.DEVICE_TYPE_RGB_LIGHT:
			mTypeTv.setText("搜索智能彩灯");
			deviceType = "智能彩灯";
			searchCmd = ConvertUtil.getInstance().convertSearchCmd(rfLight);
			break;
		case DeviceType.DEVICE_TYPE_SW_LIGHT:
			mTypeTv.setText("搜索智能色温灯");
			deviceType = "智能色温灯";
			searchCmd = ConvertUtil.getInstance().convertSearchCmd(cwLight);
			break;
		case DeviceType.DEVICE_TYPE_SWITCH:
			mTypeTv.setText("搜索智能开关");
			deviceType = "智能开关";
			searchCmd = ConvertUtil.getInstance().convertSearchCmd(rfswitch);
			break;
		case DeviceType.DEVICE_TYPE_RGB_TIAO:
			mTypeTv.setText("搜索智能灯带");
			deviceType = "智能灯带";
			searchCmd = ConvertUtil.getInstance().convertSearchCmd(rfLight2);
			break;
		default:
			break;
		}
		adjustConnectState();
	}

	private void adjustConnectState() {
		socket = SocketManager.getInstance().sMap.get(DeviceManager
				.getInstance().getmWlanId());
		if (socket != null) {
			if (socket.isLocalSuccess()) {
				initData();
				// 设置回调
				setRecvListener();
			} else {
				// 有该socket 但是socket未连接
				// 让动画先转着 隔5秒再检查是否连接成功
				if (count < 2) {
//					if (!rippleBackground.isRippleAnimationRunning()) {
//						rippleBackground.startRippleAnimation();
//					}
					if(!mSVProgressHUD.isShowing()){
						mSVProgressHUD.showWithStatus("正在搜索");
					}
					mHandler.postDelayed(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Message msg = Message.obtain();
							msg.what = 3;
							mHandler.sendMessage(msg);
							count++;
						}
					}, 5 * 1000);
				} else {
					Message msg = Message.obtain();
					msg.what = 0;
					mHandler.sendMessage(msg);
				}
			}
		} else {
			ToastShow.Show(getApplicationContext(),
					getString(R.string.search_fail));
			Intent intent = new Intent(getApplicationContext(),
					WlanSelectionActivity.class);
			startActivity(intent);
			finish();
		}
	}

	private void setRecvListener() {
		if (socket != null) {
			socket.setRecDataCallBackListener_Serach(new RecDataCallBackListener_Serach() {

				@Override
				public void onReceiveData(String data) {
					// TODO Auto-generated method stub
					if (isSearching) {

						// Log.i("wmy", "收到回调" + data);
						// 开始解析
						deviceAddress = parseData(data);
						Log.i("wmy", "得到设备地址" + deviceAddress);
						String deviceName = "";
						int deviceType = type;
						if ((deviceAddress.length() < 2)) {
							return;
						}
						if (type == DeviceType.DEVICE_TYPE_RGB_LIGHT) {// 彩灯
							deviceName = "彩灯" + deviceAddress.substring(0, 2);
						} else if (type == DeviceType.DEVICE_TYPE_RGB_TIAO) {// 彩灯
							deviceName = "彩条" + deviceAddress.substring(0, 2);
							;
						} else if (type == DeviceType.DEVICE_TYPE_SW_LIGHT) {// cw
							deviceName = "色温灯" + deviceAddress.substring(0, 2);
							;
						} else if (type == DeviceType.DEVICE_TYPE_SOCKET) {// 插座
							deviceName = "插座" + deviceAddress.substring(0, 2);
							;
						} else if (type == DeviceType.DEVICE_TYPE_SWITCH) {// 三键开关
							deviceName = "开关" + deviceAddress.substring(0, 2);
							;
						}

						Log.i("Tag", "搜索到设备 = " + deviceName);
						boolean bAdd = false;
						int isize = mDeviceList.size();
						for (int i = 0; i < isize; i++) {
							String address = mDeviceList.get(i)
									.getDeviceAddress();
							if (address.equals(deviceAddress)) {
								bAdd = true;
								break;
							}
						}
						// 用来检查以当前搜索用的网关id为mainid的设备中，是否有该彩灯
						bAdd = DeviceManager.getInstance().checkExist(
								deviceAddress);

						if (!bAdd) {
							Device devices = new Device();
							devices.setDeviceAddress(deviceAddress);
							devices.setDeviceBrand(deviceAddress);
							devices.setDeviceType(deviceType);
							devices.setDeviceName(deviceName);
							devices.setMainDeviceId(DeviceManager.getInstance()
									.getmWlanId());
							boolean e = false;
							for (int i = 0; i < mDeviceList.size(); i++) {
								if (mDeviceList.get(i).getDeviceAddress()
										.equals(deviceAddress)) {
									e = true;
								}
							}
							if (e) {

							} else {
								mDeviceList.add(devices);
							}

						}
					}
				}
			});
		}

	}

	// private void upLoadDevices(final int i) {
	// final Device device = mDeviceList.get(i);
	// RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
	// params.setAsJsonContent(true);
	// JSONObject obj = new JSONObject();
	// try {
	// obj.put("deviceAddress", device.getDeviceAddress());
	// obj.put("deviceModel", device.getDeviceBrand());
	// obj.put("deviceName", device.getDeviceName());
	// obj.put("deviceType", device.getDeviceType() + "");
	// Log.e("test", "上传的type" + device.getDeviceType());
	// Log.e("test", "上传的type" + device.getDeviceType());
	// Log.e("test", "上传的type" + device.getDeviceType());
	// obj.put("deviceVersion", "1.0");
	// obj.put("deviceWifiSSID", DeviceManager.getInstance()
	// .getmWlanBssid());
	// obj.put("deviceId", "0");
	// obj.put("hid", DeviceManager.getInstance().hid);
	// obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
	// switch (type) {
	// case DeviceType.DEVICE_TYPE_SOCKET:
	// obj.put("productId", "3");
	// obj.put("classification", "2");
	// break;
	// case DeviceType.DEVICE_TYPE_RGB_LIGHT:
	// obj.put("productId", "2");
	// obj.put("classification", "2");
	// break;
	// case DeviceType.DEVICE_TYPE_SWITCH:
	// obj.put("productId", "2");
	// obj.put("classification", "2");
	// break;
	// default:
	// break;
	// }
	// obj.put("key", "10000");
	// obj.put("requestTime", "" + System.currentTimeMillis());
	// obj.put("token",
	// (String) SPUtils.get(getApplicationContext(), "token", ""));
	//
	// Log.d("Tag", " upload obj = " + obj.toString());
	// } catch (JSONException e1) {
	// e1.printStackTrace();
	// }
	// params.setBodyContent(obj.toString());
	// x.http().post(params, new Callback.CommonCallback<String>() {
	// @Override
	// public void onSuccess(String result) {
	// Log.i("Tag", result);
	// try {
	// JSONObject jo = new JSONObject(result);
	// String resultCode = jo.getString("resultCode");
	// if (resultCode.equals("1")) {
	// // 上传成功，保存到本地
	// String deviceId = jo.getString("data");
	// Message msg = Message.obtain();
	// msg.what = 1;
	// msg.arg1 = i;
	// mHandler.sendMessage(msg);
	// } else {
	// String deviceId = jo.getString("data");
	// Message msg = Message.obtain();
	// msg.what = 2;
	// msg.obj = device.getDeviceName() + "已被绑定";
	// mHandler.sendMessage(msg);
	// }
	// } catch (JSONException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	//
	// @Override
	// public void onCancelled(CancelledException arg0) {
	//
	// }
	//
	// @Override
	// public void onError(Throwable arg0, boolean arg1) {
	//
	// }
	//
	// @Override
	// public void onFinished() {
	//
	// }
	//
	// });
	// }

	private void initData() {
		// showSearchDialog(10 * 1000);
		searching = true;
//		if (!rippleBackground.isRippleAnimationRunning()) {
//			rippleBackground.startRippleAnimation();
//		}
		if(!mSVProgressHUD.isShowing()){
			mSVProgressHUD.showWithStatus("正在搜索");
		}
		serachLightDevice();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(20 * 1000);
					isSearching = false;
				} catch (InterruptedException e) {

					e.printStackTrace();
				}
				boolean is = false;
				if (is) {

				} else {
					Message msg = Message.obtain();
					msg.what = 0;
					msg.arg1 = 0;
					mHandler.sendMessage(msg);
				}
			}
		}).start();
	}

	private void serachLightDevice() {
		sendCmdTimes = 0;
		isSearching = true;
		socket.setNotReceiving(false);
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (sendCmdTimes < 20) {
					try {
						socket.sendMqttData(searchCmd);
						sendCmdTimes++;
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);
		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private String parseData(String data) {
		Log.i("wmy", "解析红外设备地址 = " + data);
		String deviceAddress = "";
		try {
			JSONObject jo = new JSONObject(data);
			String g = jo.getString("g");
			JSONObject jo1 = new JSONObject(g);

			JSONArray ja = jo1.getJSONArray("data");
			int[] add = new int[5];
			for (int i = 1; i < 6; i++) {
				add[i - 1] = ja.getInt(i);
			}
			for (int i = 0; i < add.length; i++) {
				if (Integer.toHexString(add[i]).length() == 1) {
					deviceAddress = deviceAddress + "0"
							+ Integer.toHexString(add[i]);
				} else {
					deviceAddress = deviceAddress + Integer.toHexString(add[i]);
				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return deviceAddress;
	}

	// private void saveLight1() {
	// mSVProgressHUD = new SVProgressHUD(this);
	// mSVProgressHUD.showWithStatus("正在提交");
	// int isize = mDeviceList.size();
	// if (isize > 0) {
	// mUpLoadCounts = 0;
	// upLoadDevices(mUpLoadCounts);
	// } else {
	//
	// }
	// }

}
